package com.sfx.concurrent.demo.concurrent.AtomicTest.CAS;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-03-14
 * Time: 20:47
 */
@Slf4j(topic = "c.LockCas")
public class LockCas {

    //0 ->无锁
    //1 ->加锁
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while(true) {
            if(state.compareAndSet(0,1)) {
                break;
            }
        }
    }
    public void unlock() {
        state.set(0);
        log.debug("unlock...");
    }

    public static void main(String[] args) {
        LockCas lockCas = new LockCas();
        new Thread(()->{
            log.debug("begin");
            lockCas.lock();
            try{
                log.debug("lock...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lockCas.unlock();
            }
        },"t1").start();
        new Thread(()->{
            log.debug("begin");
            lockCas.lock();
            try{
                log.debug("lock...");
            }finally {
                lockCas.unlock();
            }
        },"t2").start();
    }

}
